<?php
//fsocket模拟post提交

$url = "http://localhost/test/php-asynchronization-post-request/accept.php?a=a";

//print_r(parse_url($url));

//echo $query;
//sock_get($url,"user=gonn");
//sock_get($url, $query);

//fsocket模拟get提交
function sock_get($url, $query)
{
    $data = array(
    'foo'=>'bar', 
    'baz'=>'boom', 
    'site'=>'www.nowamagic.net', 
    'name'=>'nowa magic'); 
    
    $query_str = http_build_query($data);
    
    $info = parse_url($url);
    $fp = fsockopen($info["host"], 80, $errno, $errstr, 3);
    //$head = "GET ".$info['path']."?".$info["query"]." HTTP/1.0\r\n";
    $head = "GET ".$info['path']."?".$query_str." HTTP/1.0\r\n";
    $head .= "Host: ".$info['host']."\r\n";
    $head .= "\r\n";
    $write = fputs($fp, $head);
    while (!feof($fp))
    {
        $line = fread($fp,4096);
        echo $line;
    }
}

sock_post($url,"user=gonn&aa=a&bb=b&cc=c");

function sock_post($url, $query)
{   
    $info = parse_url($url);
    
    $fp = fsockopen($info["host"], 80, $errno, $errstr, 3);
    $head = "POST ".$info['path']."?".$info["query"]." HTTP/1.0\r\n";
   
    $head .= "Host: ".$info['host']."\r\n";
    $head .= "Referer: http://".$info['host'].$info['path']."\r\n";
    $head .= "Content-type: application/x-www-form-urlencoded\r\n";
    $head .= "Content-Length: ".strlen(trim($query))."\r\n";
    $head .= "\r\n";
    $head .= trim($query);
    $write = fputs($fp, $head);
    //默认阻塞 会知道返回完毕
    while (!feof($fp))
    {
        $line = fread($fp,4096);  //如果不等待这里read字节可以设128
        //echo $line; 调试时可以开启 查看发会
        //break; //不等待结果可以等返回一次后跳出
    }
    fclose($fp);


}
